package com.lib.servlet.type;

import com.alibaba.fastjson.JSON;
import com.lib.common.Constant;
import com.lib.entity.Admin;
import com.lib.entity.JsonResult;
import com.lib.entity.Type;
import com.lib.service.TypeService;
import com.lib.service.ex.DeleteServiceException;
import com.lib.service.ex.ServiceException;
import com.lib.util.ParamUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "AdminDeleteTypeServlet", value = "/admin/AdminDeleteTypeServlet.do")
public class AdminDeleteTypeServlet extends HttpServlet {
    private TypeService typeService = new TypeService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Admin admin = (Admin) request.getSession().getAttribute(Constant.SESSION_ADMIN);
        int id = Integer.parseInt(request.getParameter("id"));
        JsonResult jsonResult = null;
        try {
            typeService.deleteType(id);
            jsonResult = JsonResult.getSuccessJR();
        } catch (DeleteServiceException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_SERVICE_DELETE, e.getMessage());
        } catch (ServiceException e) {
            e.printStackTrace();
            jsonResult = new JsonResult(Constant.JSON_STATE_SERVICE_ERROR, e.getMessage());
        }
        System.out.println("----------jsonResult=" + JSON.toJSONString(jsonResult));
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(JSON.toJSONString(jsonResult));
        response.getWriter().flush();
        response.getWriter().close();
    }
}
